package com.atues.thread.lock;

public class TestSync {
     int ticked;
    public static void main(String[] args) {
        // 测试静态方法锁（类锁）
        new Thread(() -> StaticLockExample.staticMethod(), "线程A").start();//lambda表达式写法；
        new Thread(() -> StaticLockExample.staticMethod(), "线程B").start();

        // 测试实例方法锁（对象锁）
        InstanceLockExample instance1 = new InstanceLockExample();
        InstanceLockExample instance2 = new InstanceLockExample();
        new Thread(() -> instance1.instanceMethod(), "线程C").start();
        new Thread(() -> instance2.instanceMethod(), "线程D").start();
    }

}

class StaticLockExample {
    // 静态方法锁 - 锁的是 StaticLockExample.class 对象
    public static synchronized void staticMethod() {
        System.out.println(Thread.currentThread().getName() + " 进入静态同步方法");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 离开静态同步方法");
    }
}

class InstanceLockExample {
    // 实例方法锁 - 锁的是当前实例对象(this)
    public synchronized void instanceMethod() {
        System.out.println(Thread.currentThread().getName() + " 进入实例同步方法");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 离开实例同步方法");
    }
}
